define(['config', 'text!app/module/system/translate.html', 'laypage',
    'mydialog', 'autocomplete','jqGrid', 'common', 'laydate'
], function (config, viewHTML, laypage,
    mydialog, autocomplete,jqGrid,common, laydate) {
	
	var token = (cache.go("token") === 'undefined') ? 'none' : cache.go("token");

    var grid_url = "/api/translate";
    
    var orderNo;
    
    /**解析时间戳*/
    function formatDateTime(inputTime) {    
        var date = new Date(inputTime);  
        var y = date.getFullYear();    
        var m = date.getMonth() + 1;    
        m = m < 10 ? ('0' + m) : m;    
        var d = date.getDate();    
        d = d < 10 ? ('0' + d) : d;    
        var h = date.getHours();  
        h = h < 10 ? ('0' + h) : h;  
        var minute = date.getMinutes();  
        var second = date.getSeconds();  
        minute = minute < 10 ? ('0' + minute) : minute;    
        second = second < 10 ? ('0' + second) : second;   
        return y + '-' + m + '-' + d+' '+h+':'+minute+':'+second;    
    };  
    

    var model = avalon.define({
    	$id : "translate",
//    	orderInfo: {},
         // 查询条件,
    	orderNo:"",
    	
    	deliveryNoteNo:"",
        
        deliverydetailInfo:{
        	id:"",
        	uuid:"",
        	deliveryNoteNo:"",//送货单号
        	orderNo:"",//订单号
        	lotNo:"",//批次号
        	name:"",//品名
        	model:"",//规格
        	color:"",//颜色
    		amount:""//总数
        },
        deliveryInfo:{
        	id:"",
     		uuid:"",
     		deliveryNoteNo:"",//送货单号
     		consignee:"",//收货人
     		modeOfShipment:"",//装运方式
     		shippingTerms:"",		//装运条款
     		mailingAddress:"",//邮寄地址
     		deliverDate:"",//发货日期
     		carrier:"",//承运人
     		carrierPhone:"",//成员人电话
     		recipient:"",//签收人
     		signTime:"",//签收时间
     		status:"0"//状态
    	},
    	signInfo:{
    		recipient:"",//签收人
     		signTime:""//签收时间
    	},
        query: {
        },
        queryProduction:{
        },
         statusArr: [],
         selected: [],
         roles: [],
         init: function () {
             model.loadGrid();
//             model_detail.loadAexgGrid();
             model.addEvent();
             model.loadGrid_d();
         },
         loadGrid: function () {
             function t(val, opt, row) {
                 
            	 var html_con = '<div class="operating" data-id="' + row.id + '"><span class="fa fa-edit mrb" title="修改"><a href="index.html#!/108"/></span><span class="fa fa-trash-o mrb" title="删除"></span>' + (row.is_deleted == 1 ? '<span class="fa fa-reply mrb" title="恢复"></span>' : '') + '</div>';
            	 return html_con;
             }
           var i = Public.setGrid();
             
             $("#grid").jqGrid({
                 loadBeforeSend: function (jqXHR) {
                     jqXHR.setRequestHeader("X-AuthToken", token);
                 },
                 datatype: "json",
                 mtype: "POST",
                 url: grid_url+"/list",
                 postData: model.query.$model,
                 loadComplete: function (data) {},
                 loadError: function (xhr, status, error) {
                     alert(JSON.parse(xhr.responseText).msg);
                 },
                 colModel: [{
                         name: "operating",
                         label: "操作",
                         width: '5%',
                         formatter: t,
                     },
                     {
                         name: "status",
                         label: "状态",
                         width: '10%',
                         formatter:function(value){
                        	 if(value===0){
                        		 return '草稿';
                        	 }else if(value===1){
                        		 
                        		 return '配载中';
                        	 }else if(value === 2){
                        		 return '已签收';
                        	 }else{
                        		 return '草稿';
                        	 }
                         },
                     },
                     {
                         name: "deliveryNoteNo",
                         label: "送货单号",
                         width: '13%',
                     },
                     {
                         name: "consignee",
                         label: "收货人",
                         width: '10%',
                     },
                     {
                         name: "modeOfShipment",
                         label: "装运方式",
                         width: '10%',
                     },
                     {
                         name: "shippingTerms",
                         label: "装运条款",
                         width: '10%',
                     },
                     {
                         name: "carrier",
                         label: "承运人",
                         width: '10%',
                     },
                     {
                         name: "carrierPhone",
                         label: "承运人电话",
                         width: '10%',
                     },
                     {
                    	 name:"recipient",
                    	 label:"签收人",
                    	 width:"10%",
                     },
                     {
                    	 name:"signTime",
                    	 label:"签收时间",
                    	 width:"10%",
                     },
                     {
                         name: "deliverDate",
                         label: "发货日期",
                         width: '10%',
                     }
                 ],
                 cmTemplate: {
                     sortable: false,
                     title: false,
                     align: "center"
                 },
                 //分页
                 page: 1,
                 rowNum: 10,
                 rowList: [10, 20, 30],
                 height: 300,
                 autowidth: true,
                 pager: '#page',
                 sortname: 'id',
                 viewrecords: true,
                 forceFit: false,
                 rownumbers: true,
                 multiselect: true,
                 multiboxonly: true,
                 sortorder: "desc",
                 /* 单击行数据   显示从表*/
                 onSelectRow: function(rowId) {
                	 
                     model.deliveryNoteNo = $("#grid").jqGrid("getRowData", rowId).deliveryNoteNo;
                     console.log("点击获取："+model.deliveryNoteNo);
                     model.reLoadGrid_d();
                 },
                 jsonReader: {
                     root: "data.list",
                     records: "data.totalRow",
                     total: "data.totalPage",
                     repeatitems: false,
                     id: "id"
                 },
                 loadError: function () {
                     parent.Public.tips({
                         type: 1,
                         content: "加载数据异常！"
                     })
                 }
             });
         },
        loadGrid_d: function () {
        	function t(val, opt, row) {
                
           	 var html_con = '<div class="operating" data-id="' + row.id + '"><span class="fa fa-edit mrb" title="修改"><a href="index.html#!/108"/></span><span class="fa fa-trash-o mrb" title="删除"></span>' + (row.is_deleted == 1 ? '<span class="fa fa-reply mrb" title="恢复"></span>' : '') + '</div>';
           	 return html_con;
            }
            $("#grid_d").jqGrid({
                loadBeforeSend: function (jqXHR) {
                    jqXHR.setRequestHeader("X-AuthToken", token);
                },
                datatype: "json",
                url: grid_url+"/getdetail",
                mtype: 'POST',
                postData: {
                    "deliveryNoteNo" : model.deliveryNoteNo
                },
                loadComplete: function (data) {
                	for (var i = 0; i < data.length; i++) {
                		console.log('[data.orderNo]',data[i].orderNo);
                		orderNo = data[i].orderNo
					}
                },
                loadError: function (xhr, status, error) {
//                             alert(JSON.parse(xhr.responseText).msg);
                },
                colModel: [
                {
                    name: "orderNo",
                    label:"订单号",
                    width: '10%',
                },
                {
                    name: "name",
                    label: "品名",
                    width: '8%',
                },
                {
                    name: "model",
                    label: "规格",
                    width: '10%',
                },
                {
                    name: "amount",
                    label: "总件",
                    width: '13%',
                },
                {
	            	name:"pn",
	                label:"料号",
	            	width:'10%',
	            	hidden:true
	            },
	            {
	            	name:"sku",
	            	label:"sku",
	            	width:'10%',
	            },
	            {
                    name: "stowageNo",
                    label: "配载数量",
                    width: '7%',
                }],
                cmTemplate: {
                    sortable: false,
                    title: false
                },
                page: 1,
                rowNum: 10,
                rowList: [10, 20, 30],
                pager: '#page_d',
                sortname: 'id',
                viewrecords: true,
                forceFit: false,
                rownumbers: true,
                multiselect: true,
                multiboxonly: true,
                sortorder: "desc",
                autoScroll: false,
                height: 150,
                altRows: true,
                gridview: true,
                autowidth: true,
                jsonReader: {
                    root: "data.list",
                    records: "data.totalRow",
                    total: "data.totalPage",
                },

            });
        },
        reLoadGrid: function () {
            $("#grid").jqGrid("setGridParam", {
            	url: grid_url+"/list",
                datatype : "json",
                mtype : "POST",
                page:1,
                postData:{
                }
            }).trigger("reloadGrid");
        },
        reLoadGrid_d: function () {
            $("#grid_d").jqGrid("setGridParam", {
                url: grid_url+"/getdetail",
                datatype : "json",
                mtype : "POST",
                page:1,
                postData:{
                	"deliveryNoteNo" : model.deliveryNoteNo
                }
            }).trigger("reloadGrid");
        },
         reset: function () {
             model.queryData();
         },
         queryData: function () {
             $("#grid").jqGrid("setGridParam", {
                 url: grid_url+"/list",
                 datatype: "json",
                 mtype: 'POST',
                 page:1,
                 postData: model.query.$model
             }).trigger("reloadGrid");
         },
        
         /**审核订单*/
         examine:function(ids,rowData){
        	 console.log('this is [ids]````````',ids);
        	 console.log('[this is rowData]',rowData);
        	 
        	 dialog({
                 title: "确认操作",
                 content: "确定通过审核？ ",
                 okValue: "确定",
	        	 ok: function () {
	        		 $.ajax({
	        		 type:"POST",
	        		 url:"/api/translate/toExamine",
	        		 data:{
	        			ids :ids,
	        			orderNo:orderNo,
	             		deliveryNoteNo:rowData.deliveryNoteNo
	        		 },
	        		 success: function (data) {
	        			 
	        			 console.log('data111111111111111',data.success);
	        			 
	        			 if(data.success){
	        				 dialog({
		                         title: "保存成功",
		                         content: "保存成功!",
		                         okValue: "确定",
		                         ok: function() {}
		                     }).showModal();
	        			 }else if(!data.success){
	        				 dialog({
	        					 title: "错误",
	        					 content: data.msg,
	        					 okValue: "确定",
	        					 ok: function() {	        				 
	        						 window.history.go(0);
	        					 }
	        				 }).showModal();
	        			 }	        			 
	        			 model.reLoadGrid();
	        		 },
	        		 beforeSend: function (xhr) {
	                     xhr.setRequestHeader("X-AuthToken", token);
	                 },
	                 error: function (responseData, textStatus, errorThrown) {
	                     alert("Failed: " + responseData);
	                 }
	        	 });
	        	 },
	        	 cancelValue: "取消",
                 cancel: function () {} 
        	 }).showModal();
         },
         sign:function(rowData){
        	 dialog({
                 title: "签收",
                 content:$('#editUser'),
                 okValue: "确定",
                 ok: function () {
                	 console.log('rowData',rowData);
                	 console.log('model.deliveryInfo',model.signInfo.$model);
                	 console.log('model.deliveryInfo.recipient',model.signInfo.$model.recipient);
                	 console.log('model.deliveryInfo.signTime',model.signInfo.$model.signTime);
	                     $.ajax({
                         type: "POST",
                         url: "/api/translate/sign",
                         data: {
                             "deliveryNoteNo": rowData.deliveryNoteNo,
                             "recipient":model.signInfo.$model.recipient,
                             "signTime":model.signInfo.$model.signTime
                         },
                         beforeSend: function (xhr) {
                             xhr.setRequestHeader("X-AuthToken", token);
                         },
                         success: function (data, status, xhr) {
                        	 
                        	 if(data.success){
                        		 dialog({
                                     title: "签收",
                                     content: "签收成功",
                                     okValue: "确定",
                                     ok: function () {
                                     },
                                 }).showModal();
                        	 }else if(!data.success){
                        		 dialog({
                                     title: "错误",
                                     content: "未知错误导致签收失败！",
                                     okValue: "确定",
                                     ok: function () {
                                     },
                                 }).showModal();
                        	 }
                        	 model.reLoadGrid();
                         },
                         error: function (responseData, textStatus, errorThrown) {
                             alert("Failed: " + responseData);
                         }

                     });
                 },
                 cancelValue: "取消",
                 cancel: function () {}
             }).showModal();
         },
         /**删除订单*/
         del: function (ids) {
             dialog({
                 title: "确认操作",
                 content: "确定删除？ 此操作不可恢复！",
                 okValue: "确定",
                 ok: function () {
                     $.ajax({
                         type: "POST",
                         url: "/api/translate/delete",
                         data: {
                             "ids": ids
                         },
                         beforeSend: function (xhr) {
                             xhr.setRequestHeader("X-AuthToken", token);
                         },
                         success: function (data, status, xhr) {
                             if (data) {
                                 $('#grid').jqGrid('delRowData', ids);
                                 dialog({
                                     title: "删除成功",
                                     content: "删除成功！",
                                     okValue: "确定",
                                     ok: function () {
                                     },
                                     cancelValue: "取消",
                                     cancel: function () {}
                                 }).showModal();
                             }
                             model.queryData();
                         },
                         error: function (responseData, textStatus, errorThrown) {
                             alert("Failed: " + responseData);
                         }

                     });
                 },
                 cancelValue: "取消",
                 cancel: function () {}
             }).showModal();
         },
         addEvent: function () {

        	 /**打开新的table 跳转页面*/
        	 $(".fr").on("click", "#add", function (e) {
        		 top.topManager.openPage({
        			id:"addOrder",
        			title:"新建送货单",
        			href:'index.html#!/116?deliveryNoteNo=',
        			reload:true
        		 })
        	 });
        	 $("#sign").on("click",function (e) {
        		 var t = $("#grid").jqGrid("getGridParam", "selarrrow");
                 var rowData = $("#grid").jqGrid('getRowData',t);
                 console.log("rowData",rowData);
                 if(JSON.stringify(rowData) == "{}"){
                	 dialog({
                         title: "错误",
                         content: "请选择要签收的运输单！",
                         okValue: "确定",
                         ok: function () {
                         },
                     }).showModal();
                 }else if(rowData.status === '草稿'){
                	 dialog({
                         title: "错误",
                         content: "未审核订单不能签收！",
                         okValue: "确定",
                         ok: function () {
                         },
                     }).showModal();
                 }else if(rowData.recipient){
                	 dialog({
                         title: "错误",
                         content: "请勿重复签收操作！",
                         okValue: "确定",
                         ok: function () {
                         },
                     }).showModal();
                 }else{
                	 model.initproduction();
                	 model.sign(rowData);
                 }
        	 });
        	 
        	 var t = this;
        	 //修改订单信息
        	 $(".grid-wrap").on("click", ".fa-edit", function (e) {
                 var t = $(this).parent().data("id");
                 var rowData = $("#grid").jqGrid('getRowData',t);
                 var deliveryNoteNo = rowData.deliveryNoteNo;
                 top.topManager.openPage({
         			id:"addOrder",
         			title:"修改送货单",
         			href:'index.html#!/116?deliveryNoteNo='+deliveryNoteNo,
         			reload:true
         		 })
             });
              //订单审核
             $("#examine").on("click",function (e) {
            	 var t = $("#grid").jqGrid("getGridParam", "selarrrow");
                 var rowData = $("#grid").jqGrid('getRowData',t);
                 console.log("rowData.status",rowData.status);
                 if(rowData.status == '草稿'){
                	 e.preventDefault();
                     // if (Business.verifyRight("BU_DELETE")) {
                     t.length ? model.examine(t.join(),rowData) : parent.Public.tips({
                         type: 2,
                         content: "请选择要审核的订单！"
                     })
                 }else{
                	 dialog({
                         title: "错误",
                         content: "请勿重复审核操作！",
                         okValue: "确定",
                         ok: function () {
                         },
                     }).showModal();
                 }
            	  
             });
             // 删除
             $(".grid-wrap").on("click", ".fa-trash-o", function (t) {
            	 var t = $("#grid").jqGrid("getGridParam", "selarrrow");
                 var rowData = $("#grid").jqGrid('getRowData',t);
            	 if(rowData.status === '草稿' ){
            		 var ei = [];
                     var e = $(this).parent().data("id");
                     ei.push(e);
                     model.del(e);
            	 }else{
            		 dialog({
                         title: "错误",
                         content: "已审核请勿删除!",
                         okValue: "确定",
                         ok: function() {}
                     }).showModal();
            	 }
                 
             });
             $("#search").click(function (e) {
                 e.preventDefault();
                 model.queryData();
             });
             $(".fa-refresh").click(function (e) {
                 e.preventDefault();
                 model.reset();
                 model.queryData();
             })
             $("#btn-batchDel").click(function (e) {
                 e.preventDefault();
                 // if (Business.verifyRight("BU_DELETE")) {
                 var t = $("#grid").jqGrid("getGridParam", "selarrrow");
                 t.length ? model.del(t.join()) : parent.Public.tips({
                     type: 2,
                     content: "请选择需要删除的项"
                 })
             });
         },
         initorder: function () {
	        	 model.deliverydetailInfo={
	             	id:"",
	             	uuid:"",
	             	deliveryNoteNo:"",//送货单号
	             	orderNo:"",//订单号
	             	lotNo:"",//批次号
	             	name:"",//品名
	             	model:"",//规格
	             	color:"",//颜色
	         		amount:""//总数
	             }
            		 
             },
         initproduction:function(){
        	 model.deliveryInfo = {
             	id:"",
          		uuid:"",
          		deliveryNoteNo:"",//送货单号
          		consignee:"",//收货人
          		modeOfShipment:"",//装运方式
          		shippingTerms:"",		//装运条款
          		mailingAddress:"",//邮寄地址
          		deliverDate:"",//发货日期
          		carrier:"",//承运人
          		carrierPhone:"",//成员人电话
          		recipient:"",//签收人
          		signTime:"",//签收时间
          		status:"0"//状态
         	}
           }
    })
    // 定义视图模块
    var viewmod = {
        viewtSrc: viewHTML,
        viewInit: function () {
            model.init();
        }, // 模块view加载完成后的回调方法，在刷新（F5）时可能调用两次
        viewDestroy: function () {} // 切换菜单时销毁原来的view
    };
    return viewmod;
});
